package cn.enzo.utils.db;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

@MappedJdbcTypes(JdbcType.CHAR)
@MappedTypes({IntEnum.class})
public class EnumTypeHandler<E extends Enum<E>> extends BaseTypeHandler<IntEnum<E>> {

	
	
	private Class<IntEnum<E>> type;  
	  
    public EnumTypeHandler(Class<IntEnum<E>> type) {  
        if (type == null)  
            throw new IllegalArgumentException("Type argument cannot be null");  
        this.type = type;  
    }
	
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, IntEnum<E> parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setInt(i, parameter.getIndex());
		
	}

	@Override
	public IntEnum<E> getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return covertEnmu(rs.getInt(columnName));
	}

	@Override
	public IntEnum<E> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return covertEnmu(rs.getInt(columnIndex));
	}

	@Override
	public IntEnum<E> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return covertEnmu(cs.getInt(columnIndex));
	}


	private IntEnum<E> covertEnmu(int index){
		IntEnum<E>[] constants = type.getEnumConstants();
		for (IntEnum<E> intEnum : constants) {
			if(intEnum.getIndex() == index){
				return intEnum;
			}
		}
		return type.getEnumConstants()[0];
	}
}
